/**
 * author:wos
 * time:2024-1-4
 * title:根据角色查询目录权限
 */

const parseQueryParams = require("../../../utils/parseQueryParams");

async function list(ctx, next) {

    const url = ctx.request.url
    const query = parseQueryParams(url)

    // 用户已选
    let checkedKeys = []
    if (query.roleId != undefined){
        const sql = `select * from sys_role_menu where roleId = ${query.roleId}`
        let rs = await global.query(sql)
        for (let i in rs){
            checkedKeys.push(rs[i].menuId)
        }
    }

    // 目录树
    let menu = await global.query(`select * from sys_menu where status = '0' order by orderNum asc`)
    let data = formatMenu(menu, 0)

    try {
        global.response(ctx, {
            "status":200,
            "code": 200,
            "data": {
                checkedKeys:checkedKeys,
                menus:data
            },
            "msg":'success'
        })
    } catch (err) {
        global.serverError(ctx)
    }
}


/**
 * 格式化目录菜单
 * @param menu
 * @param parentId
 * @returns {[]}
 */
function formatMenu(menu, parentId){
    let result = []
    for(let i in menu){
        if(menu[i].parentId == parentId){
            let item = {
                "id": menu[i].menuId,
                "label": menu[i].menuName
            }
            let children = formatMenu(menu, menu[i].menuId)
            if(children.length > 0){
                item.children = children
            }
            result.push(item)
        }
    }
    //排序
    result.sort((a, b) => {
        return Number(a.orderNum) - Number(b.orderNum);
    })
    return result
}
module.exports = list


